from django_filters import rest_framework as filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime

from inventory.serializers import InventoryCheckSerializer, InventoryCheckDetailSerializer
from inventory.models import InventoryCheck, InventoryCheckDetail, InventoryCheckStatus
from utils.custom_model_viewSet import CustomModelViewSet


class InventoryCheckFilter(filters.FilterSet):
    """
    库存盘点过滤类，用于盘点列表过滤
    """
    check_code = filters.CharFilter(field_name='check_code', lookup_expr='icontains')
    warehouse_name = filters.CharFilter(field_name='warehouse__warehouse_name', lookup_expr='icontains')
    check_date_range = filters.DateFromToRangeFilter(field_name='check_date')
    
    class Meta:
        model = InventoryCheck
        fields = [
            'check_id', 'check_code', 'warehouse', 'status', 
            'check_date', 'checker_id', 'approver_id'
        ]


class InventoryCheckViewSet(CustomModelViewSet):
    """
    库存盘点视图集，提供盘点的增删改查操作
    """
    queryset = InventoryCheck.objects.filter(is_deleted=False).order_by('-check_date')
    serializer_class = InventoryCheckSerializer
    filterset_class = InventoryCheckFilter
    search_fields = ['check_code', 'warehouse__warehouse_name']
    ordering_fields = ['check_date', 'create_time', 'check_id']
    ordering = ['-check_date']
    enable_soft_delete = True
    
    @action(detail=True, methods=['post'], url_path='start-check')
    def start_check(self, request, pk=None, *args, **kwargs):
        """
        开始库存盘点
        
        Args:
            request: HTTP请求对象
            pk: 盘点单ID
        
        Returns:
            Response: 盘点开始结果
        """
        try:
            inventory_check = self.get_object()
            
            # 检查盘点单状态
            if inventory_check.status != InventoryCheckStatus.CREATED:
                return Response({
                    'code': status.HTTP_400_BAD_REQUEST,
                    'message': f'盘点单状态为{inventory_check.status}，无法开始盘点'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新盘点单状态和开始时间
            inventory_check.status = InventoryCheckStatus.IN_PROGRESS
            inventory_check.start_time = datetime.now()
            inventory_check.save()
            
            return Response({
                'code': status.HTTP_200_OK,
                'message': '盘点已开始'
            })
        except Exception as e:
            return Response({
                'code': status.HTTP_400_BAD_REQUEST,
                'message': f'开始盘点失败：{str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['post'], url_path='complete-check')
    def complete_check(self, request, pk=None, *args, **kwargs):
        """
        完成库存盘点
        
        Args:
            request: HTTP请求对象
            pk: 盘点单ID
        
        Returns:
            Response: 盘点完成结果
        """
        try:
            inventory_check = self.get_object()
            
            # 检查盘点单状态
            if inventory_check.status != InventoryCheckStatus.IN_PROGRESS:
                return Response({
                    'code': status.HTTP_400_BAD_REQUEST,
                    'message': f'盘点单状态为{inventory_check.status}，无法完成盘点'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新盘点单状态和结束时间
            inventory_check.status = InventoryCheckStatus.COMPLETED
            inventory_check.end_time = datetime.now()
            
            # 计算盘点差异（这里简化处理，实际项目中可能需要更复杂的逻辑）
            details = inventory_check.details.filter(is_deleted=False)
            total_variance_quantity = sum(detail.variance_quantity for detail in details)
            total_variance_amount = sum(detail.variance_amount for detail in details)
            
            inventory_check.total_variance_quantity = total_variance_quantity
            inventory_check.total_variance_amount = total_variance_amount
            inventory_check.save()
            
            return Response({
                'code': status.HTTP_200_OK,
                'message': '盘点已完成',
                'data': {
                    'total_variance_quantity': float(total_variance_quantity),
                    'total_variance_amount': float(total_variance_amount)
                }
            })
        except Exception as e:
            return Response({
                'code': status.HTTP_400_BAD_REQUEST,
                'message': f'完成盘点失败：{str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)


class InventoryCheckDetailFilter(filters.FilterSet):
    """
    库存盘点明细过滤类，用于盘点明细列表过滤
    """
    check_code = filters.CharFilter(field_name='inventory_check__check_code', lookup_expr='icontains')
    product_name = filters.CharFilter(field_name='product__name', lookup_expr='icontains')
    product_sku = filters.CharFilter(field_name='product__sku', lookup_expr='icontains')
    location_code = filters.CharFilter(field_name='location__location_code', lookup_expr='icontains')
    
    class Meta:
        model = InventoryCheckDetail
        fields = [
            'detail_id', 'inventory_check', 'product', 'location', 
            'system_quantity', 'actual_quantity', 'variance_quantity', 
            'lot_number', 'serial_number'
        ]


class InventoryCheckDetailViewSet(CustomModelViewSet):
    """
    库存盘点明细视图集，提供盘点明细的增删改查操作
    """
    queryset = InventoryCheckDetail.objects.filter(is_deleted=False).order_by('inventory_check', 'product')
    serializer_class = InventoryCheckDetailSerializer
    filterset_class = InventoryCheckDetailFilter
    search_fields = [
        'inventory_check__check_code', 'product__name', 
        'product__sku', 'location__location_code', 
        'lot_number', 'serial_number'
    ]
    ordering_fields = ['inventory_check', 'product', 'location', 'create_time', 'detail_id']
    ordering = ['inventory_check', 'product', 'location']
    enable_soft_delete = True